/*
 * Copyright (C) 2011 Johan Kannala
 *
 * Licensed under the MIT License. You can find a copy of the License at in the
 * license.txt file.
 */
package com.joppe.vocabtutor;

import android.app.Activity;
import android.content.*;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.EditText;

/**
 * @author joppe
 *
 */
public class CreateChapterActivity extends LoggedActivity {
    private VocabTutor mApplication = null;
    private Long mBookId = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (VocabTutor) this.getApplication();
        Intent intent = getIntent();
        Bundle extraInfo = intent.getExtras();
        if (extraInfo != null && extraInfo.containsKey("book_id")) {
            mBookId = extraInfo.getLong("book_id");
        }
        if (mBookId == 0L)
            throw new IllegalArgumentException("No book id passed to create chapter activity.");
        
        requestWindowFeature(Window.FEATURE_LEFT_ICON);
        setContentView(R.layout.createchapter_activity);
        getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
            android.R.drawable.ic_dialog_alert);
    }
    
    public void createChapter(View button) {
        EditText chapterName = (EditText) findViewById(R.id.createchapter_name_fld);
        Log.i("event_notification", "New chapter created: "
                + chapterName.getText().toString());
        SQLiteDatabase db = null;
        try {
            db = mApplication.getDataHelper()
                    .getWritableDatabase();
            ContentValues content = new ContentValues();
            content.put("title", chapterName.getText().toString());
            content.put("book_fk", mBookId);
            long chapterId = db.insert("chapters", null, content);
            if (chapterId == -1) {
                Log.e("com.joppe.vocabtutor", "Chapter creation returned -1?");
            }
            Intent result = new Intent();
            result.putExtra("book_id", mBookId);
            result.putExtra("chapter_id", chapterId);
            setResult(Activity.RESULT_OK, result);
            finish();
        }
        catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
